package com.yidaozou.interceptor;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.yidaozou.jsonobj.req.Body;
import com.yidaozou.jsonobj.req.Message;
import com.yidaozou.jsonobj.req.TypeBody;
import com.yidaozou.test.jsonobj.Student;

public class JsonInterceptor extends HandlerInterceptorAdapter {

	/**
	 * 最后执行，可用于释放资源
	 */
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	/**
	 * 显示视图前执行
	 */
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}
	

	/**
	 * Controller之前执行
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		request.setCharacterEncoding("UTF-8");
		BufferedReader reader = request.getReader();
		String line = null;
		StringBuffer inputString = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			inputString.append(line);
		}
		System.out.println("接收到的报文：["+inputString+"]");
		JSONObject jsonMessage = JSONObject.fromObject(inputString.toString());
		JSONObject jsonHead = jsonMessage.getJSONObject("head");
		JSONObject jsonBody = jsonMessage.getJSONObject("body");
		String businessCode = jsonHead.getString("businessCode");
		System.out.println("in=" + businessCode);
		
		Body body = (Body)JSONObject.toBean(jsonBody, getClassByBusinessCode(businessCode));
		System.out.println((TypeBody)body);
		
		// 返回报文
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		if(true) {
			PrintWriter out = response.getWriter();
			out.print("out=" + businessCode);
			out.flush();
			out.close();
			return false;
		}
		return super.preHandle(request, response, handler);
	}
	
	public static Class getClassByBusinessCode(String businessCode) {
		if("110001".equals(businessCode)) {
			return TypeBody.class;
		}
		return null;
	}
}
